package com.gaoyi.crm.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.gaoyi.crm.R;
import com.gaoyi.crm.adapter.ScannedAdapter;
import com.gaoyi.crm.callback.IView;
import com.gaoyi.crm.constant.ApiStatus;
import com.gaoyi.crm.constant.BundleKeyName;
import com.gaoyi.crm.constant.EventCode;
import com.gaoyi.crm.constant.RequestCode;
import com.gaoyi.crm.control.dialog.LoadingDialogUtils;
import com.gaoyi.crm.databinding.FragmentScannedListBinding;
import com.gaoyi.crm.db.bean.Event;
import com.gaoyi.crm.db.bean.ResultBean;
import com.gaoyi.crm.db.entity.ItemNoStore;
import com.gaoyi.crm.db.entity.Pmn;
import com.gaoyi.crm.db.query.BaseQuery;
import com.gaoyi.crm.fragment.base.BaseListFragment;
import com.gaoyi.crm.util.PermissionUtils;
import com.gaoyi.crm.util.ToastUtil;
import com.gaoyi.crm.util.Utils;
import com.gaoyi.crm.vm.ScannedListViewModel;
import com.gs.zxinglibrary.zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ScannedListFragment extends BaseListFragment<FragmentScannedListBinding, ScannedListViewModel, ItemNoStore, BaseQuery> implements IView {

    private boolean mIsEdit, mIsRecordEdit;
    private ScannedAdapter mAdapter;
    private Pmn mPmnDto;
    private ActivityResultLauncher<Intent> mScanResult;
    private String mId;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_scanned_list;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mPermissionsResult = registerForPermissionsResult();
        mScanResult = registerForActivityResult(RequestCode.REQUEST_SCAN);
        MyOnClickListener onClickListener = new MyOnClickListener();
        mBinding.tvBack.setOnClickListener(onClickListener);
        mBinding.btnSync.setOnClickListener(onClickListener);
        mBinding.btnSave.setOnClickListener(onClickListener);
        mBinding.btnEdit.setOnClickListener(onClickListener);
        mBinding.btnAdd.setOnClickListener(onClickListener);
        mBinding.btnDelete.setOnClickListener(onClickListener);
        mAdapter = new ScannedAdapter(mContext);
        mBinding.rvNew.setLayoutManager(new LinearLayoutManager(mContext));
        mBinding.rvNew.setAdapter(mAdapter);
    }

    private RelativeLayout.LayoutParams initBtn() {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mBinding.btnSave.getLayoutParams();
        if (mIsRecordEdit) { // 修改Record，只显示Save按钮
            mBinding.btnSync.setVisibility(View.GONE);
            lp.addRule(RelativeLayout.CENTER_HORIZONTAL, 0);
        } else {
            boolean online = Utils.isOnline();
            mBinding.btnSync.setVisibility(online ? View.VISIBLE : View.GONE);
            lp.addRule(RelativeLayout.CENTER_HORIZONTAL, online ? 1 : 0);
        }
        return lp;
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.tvBack) {
//                onBackPressed();
                mContext.onBackPressed();
            } else if (id == R.id.btnSync) {
                sync();
            } else if (id == R.id.btnSave) {
                save();
            } else if (id == R.id.btnEdit) {
                edit();
            } else if (id == R.id.btnAdd) {
                add();
            } else if (id == R.id.btnDelete) {
                delete();
            }
        }
    }

    public void onBackPressed(){
        if (!mIsRecordEdit) {
            Bundle bundle = new Bundle();
            List<ItemNoStore> itemNoStores = mViewModel.getList().getValue();
            ArrayList<ItemNoStore> list = new ArrayList<>();
            if (itemNoStores != null && !itemNoStores.isEmpty()) {
                list.addAll(itemNoStores);
            }
            bundle.putParcelableArrayList(BundleKeyName.RESULT, list);
            // 将新的item list返回给newPromotion，避免重新进入此页面时没有修改到
            getParentFragmentManager().setFragmentResult(BundleKeyName.RESULT,bundle);
        }
    }

    private void delete() {
        List<ItemNoStore> list = mAdapter.getCurrentList();
        List<ItemNoStore> unCheckList = new ArrayList<>();
        for (ItemNoStore dto : list) {
            if (!dto.isCheck()) {
                unCheckList.add(dto);
            }
        }
        if (unCheckList.size() == list.size()) {
            ToastUtil.showToast(R.string.p_sel_delete_item_no);
            return;
        }
        mViewModel.setListValue(unCheckList);
    }

    private void add() {
        boolean permission = PermissionUtils.addPermission(requireActivity(), new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        }, mPermissionsResult); // 判断是否有权限
        if (permission) {
            toScan();
        }
    }

    private void toScan() {
        Utils.scan(mContext, mScanResult, 1);
    }

    private void sync() {
        mViewModel.syncPmn(mPmnDto);
    }

    private void save() {
        if (mIsEdit) { // 编辑状态下
            mIsEdit = false;
            mBinding.btnAdd.setVisibility(View.GONE);
            mBinding.btnDelete.setVisibility(View.GONE);
            mBinding.btnEdit.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams lp = initBtn();
            lp.addRule(RelativeLayout.ALIGN_PARENT_END, 0);// 修改按钮Save的位置

            changeRvCbxState();
        } else { // 数据保存在本地
            if (mIsRecordEdit) { // 修改状态下只保存itemNo
                mViewModel.saveItemNo(mId);
            } else { // 保存整个Pmn
                mViewModel.savePmn(mPmnDto);
            }
        }
    }

    private void edit() {
        mIsEdit = true;
        if (Utils.isOnline()) {
            mBinding.btnSync.setVisibility(View.GONE);
        }
        mBinding.btnEdit.setVisibility(View.GONE);
        mBinding.btnAdd.setVisibility(View.VISIBLE);
        mBinding.btnDelete.setVisibility(View.VISIBLE);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mBinding.btnSave.getLayoutParams();
        lp.addRule(RelativeLayout.CENTER_HORIZONTAL, 0);
        lp.addRule(RelativeLayout.ALIGN_PARENT_END);

        changeRvCbxState();
    }

    /**
     * 修改列表是否显示复选框
     */
    private void changeRvCbxState() {
        mAdapter.setShowCbx(mIsEdit);
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        if (bundle == null) {
            return;
        }
        mIsRecordEdit = bundle.getBoolean(BundleKeyName.IS_EDIT, false);
        if (mIsRecordEdit) {
            mId = bundle.getString(BundleKeyName.ID);
            mBinding.tvBack.setVisibility(View.GONE);
            mViewModel.getItemNoList(mId);
        } else {
            mBinding.tvBack.setVisibility(View.VISIBLE);
            mPmnDto = bundle.getParcelable(BundleKeyName.RESULT);
            if (mPmnDto == null) {
                return;
            }
            List<ItemNoStore> data = mPmnDto.getItemNos();
            if (data != null && !data.isEmpty()) {
                mViewModel.addListValue(data);
            }
        }
        initBtn();
    }

    @Override
    protected void initLiveData() {
        mViewModel.getList().observe(getViewLifecycleOwner(), itemNoStoreDtos -> {
            mAdapter.submitList(itemNoStoreDtos);
            mBinding.tvTotal.setText(getString(R.string.total_num, itemNoStoreDtos.size()));
        });
        mViewModel.getResultCode().observe(getViewLifecycleOwner(), this::uploadResult);
        mViewModel.getResult().observe(getViewLifecycleOwner(), this::jumpToResult);
    }

    private void jumpToResult(ResultBean result) {
        if (result == null) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putParcelable(BundleKeyName.RESULT, result);
        mController.navigate(R.id.action_scannedListFragment_to_resultFragment, bundle);
    }

    private void uploadResult(Integer result) {
        if (result == ApiStatus.SUCCESS) {
            if (mIsRecordEdit) {
                ToastUtil.showToast(R.string.save_successful);
            } else {
                ResultBean bean = new ResultBean(ApiStatus.SUCCESS, getString(R.string.create_new_pmn_success), "", ScannedListFragment.class.getSimpleName());
                jumpToResult(bean);
            }
        }
    }

    @Override
    protected void loadData() {

    }

    @Override
    protected void search(Date startDate, Date endDate) {

    }

    @Override
    protected void search(String keyWord) {

    }

    @Override
    protected void sort(int id, Integer sort) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        if (event.getWhat() == EventCode.EVENT_NET_STATE) {
            if (mIsEdit) return;
            initBtn();
        }
    }

    @Override
    protected BaseQuery createQuery() {
        return null;
    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {
        if (PermissionUtils.requestPermissionResult(result, Manifest.permission.CAMERA)
                && PermissionUtils.requestPermissionResult(result, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            toScan();
        } else {
            ToastUtil.showToast(R.string.no_permission);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {
        if (requestCode == RequestCode.REQUEST_SCAN) {
            scanResult(result);
        }
    }

    private void scanResult(ActivityResult result) {
        Intent data = result.getData();
        if (result.getResultCode() == 0 || data == null) {
            return;
        }
        Bundle dataExtras = data.getExtras();
        if (dataExtras == null) {
            return;
        }
        if (dataExtras.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String itemNo = dataExtras.getString(CodeUtils.RESULT_STRING);
            // 判断itemNo是否已存在
            for (ItemNoStore itemNoStore : mViewModel.getList().getValue()) {
                if (itemNoStore.getItemNo().equals(itemNo)) {
                    ToastUtil.showToast(R.string.same_item_no);
                    return;
                }
            }
            mViewModel.getItemNoStore(itemNo);
        }
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }
}